import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { verifyToken } from '@/lib/auth';

export async function GET(request: NextRequest) {
  try {
    const authHeader = request.headers.get('authorization');
    if (!authHeader?.startsWith('Bearer ')) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }

    const token = authHeader.substring(7);
    const payload = await verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { error: '无效的访问令牌' },
        { status: 401 }
      );
    }

    const [
      totalPosts,
      publishedPosts,
      draftPosts,
      totalComments,
      pendingComments,
      totalUsers,
      totalViews,
      recentPosts,
      popularTags
    ] = await Promise.all([
      prisma.post.count(),
      prisma.post.count({ where: { status: 'PUBLISHED' } }),
      prisma.post.count({ where: { status: 'DRAFT' } }),
      prisma.comment.count(),
      prisma.comment.count({ where: { status: 'PENDING' } }),
      prisma.user.count(),
      prisma.post.aggregate({
        _sum: {
          viewCount: true
        }
      }),
      prisma.post.findMany({
        take: 5,
        orderBy: { createdAt: 'desc' },
        include: {
          author: { select: { name: true } },
          tags: { include: { tag: true } }
        }
      }),
      prisma.tag.findMany({
        take: 10,
        orderBy: { posts: { _count: 'desc' } },
        include: {
          _count: {
            select: { posts: true }
          }
        }
      })
    ]);

    return NextResponse.json({
      overview: {
        totalPosts,
        publishedPosts,
        draftPosts,
        totalComments,
        pendingComments,
        totalUsers,
        totalViews: totalViews._sum.viewCount || 0
      },
      recentPosts: recentPosts.map(post => ({
        ...post,
        tags: post.tags.map(pt => pt.tag.name)
      })),
      popularTags: popularTags.map(tag => ({
        name: tag.name,
        count: tag._count.posts
      }))
    });
  } catch (error) {
    console.error('获取统计数据失败:', error);
    return NextResponse.json(
      { error: '获取统计数据失败' },
      { status: 500 }
    );
  }
}
